﻿using EYangFrame.DataAccess.Global;
using EYangFramewirk.Business.MessageSystem.Interfaces;
using EYangFramework.Domain.Entitys.Entrys;
using EYangFramework.Domain.Repositorys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EYangFramewirk.Business.MessageSystem.Implementation
{
    public class BLLDealMessage : IBLLDealMessage
    {
        private IRepository<Message> RepositoryMessage { get; set; }
        public BLLDealMessage(IRepository<Message> repositoryMessage)
        {
            this.RepositoryMessage = repositoryMessage;
        }
        public bool DealMessage(Message message,Guid lastMessageID)
        {
            if (lastMessageID != Guid.Empty)
            {
                var lastMessage = RepositoryMessage.GetAllList(t => t.ID == lastMessageID).First();
                lastMessage.ReadUser += GlobalInfo.CurrentUser.USERNAME + ",";
                lastMessage.ReadTimes += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ",";
                RepositoryMessage.Update(lastMessage);
            }
            if (message != null)
            {
                RepositoryMessage.Insert(message);
            }
            return true;
        }

        public void Dispose()
        {
            RepositoryMessage.DbContext.Dispose();
        }

        public List<Message> GetMessages(string[] currentUsers)
        {
            List<Message> messages = RepositoryMessage.GetAllNoTracking().Where(t => System.Data.Entity.DbFunctions.DiffDays(DateTime.Now, t.CREATETIME) <= 5).ToList();
            return messages.Where(t => IsCommunicationUser(t, currentUsers)).OrderBy(t => t.CREATETIME).ToList();
        }
        private bool IsCommunicationUser(Message message,string[] currentUsers)
        {
            string[] users = (message.From + "," + message.To).Split(',');
            if (users.Length != currentUsers.Length)
            {
                return false;
            }
            foreach (var item in users)
            {
                if (!currentUsers.Contains(item))
                {
                    return false;
                }
            }
            return true;
        }

        public Message GetMessageByID(Guid id)
        {
            return RepositoryMessage.GetAllNoTracking().Where(t => t.ID == id).First();
        }
    }
}
